import React from 'react';

export class List extends React.Component {
  constructor() {
    super();
    // 组件状态（数据）
    this.state = {
      list: [
        {
          id: 1,
          name: '超级好吃的棒棒糖',
          price: 18.8,
          info: '开业大酬宾，全场8折',
        },
        {
          id: 2,
          name: '超级好吃的大鸡腿',
          price: 34.2,
          info: '开业大酬宾，全场8折',
        },
        {
          id: 3,
          name: '超级无敌的冰激凌',
          price: 14.2,
          info: '开业大酬宾，全场8折',
        },
      ],
    };
  }

  // 砍价函数
  kan = (id, amount) => {
    console.log(id, amount);
    // 修改list数组中对应商品（map）
    const newList = this.state.list.map((item) => {
      if (item.id === id) {
        return { ...item, price: (item.price - amount).toFixed(2) };
      } else {
        return item;
      }
    });
    // 设置页面数据
    this.setState({
      list: newList,
    });
  };

  render() {
    return (
      // 父组件
      <div style={{ width: '80%', padding: 10, border: '2px solid black' }}>
        <h1>父组件</h1>
        {/* 把下面UI抽离为子组件 */}
        {this.state.list.map((item) => (
          <Item
            key={item.id}
            kan={this.kan}
            name={item.name}
            price={item.price}
            info={item.info}
            id={item.id}
          />
        ))}
      </div>
    );
  }
}

class Item extends React.Component {
  render() {
    console.log(this.props);
    return (
      <div style={{ margin: 10, padding: 10, border: '2px solid skyblue' }}>
        <h3>标题：{this.props.name}</h3>
        <div>价格：{this.props.price}</div>
        <div>{this.props.info}</div>
        <button onClick={() => this.props.kan(this.props.id, 1)}>砍价</button>
      </div>
    );
  }
}

export default List;
